import { EtcdConfigService } from '@app/etcd-config';
import {
  Injectable,
  Logger,
  OnModuleDestroy,
  OnModuleInit,
} from '@nestjs/common';
import { Etcd3 } from 'etcd3';

@Injectable()
export class EtcdRegisterService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(EtcdRegisterService.name);
  private readonly etcd: Etcd3;
  private instance: any;

  constructor(private readonly etcdConfigService: EtcdConfigService) {
    this.etcd = new Etcd3({
      hosts: 'http://localhost:2379',
      auth: {
        username: 'root',
        password: '5262',
      },
    });
  }
  /**
   * 启动生命周期钩子
   */
  async onModuleInit() {}
  /**
   * 关闭生命周期钩子
   */
  async onModuleDestroy() {
    if (this.instance) {
      await this.instance.revoke();
    }
  }

  /**
   * 注册服务
   * @param serviceName
   * @param serviceHost
   * @param servicePort
   */
  async registerService(serviceName: string) {
    try {
      const res = await this.matchingService(serviceName);
      this.instance = {
        ip: res.ip,
        port: Number(res.port),
        instanceId: res.serviceId,
      };
      const lease: string = JSON.stringify(this.instance);
      await this.etcd.put(serviceName).value(lease);
      this.logger.log(`Service ${serviceName}：Etcd 注册成功`);
    } catch (error) {
      this.logger.error('Etcd 服务注册失败', error);
    }
  }

  /**
   * 注销服务
   * @param serviceName
   */
  async romoveService(serviceName: string) {
    try {
      await this.etcd.delete().key(serviceName);
      this.logger.log(`${serviceName}：Etcd 注销成功`);
    } catch (error) {
      this.logger.error('Etcd 服务注销失败', error);
    }
  }

  /**
   * 发现服务
   */
  async getAllService() {
    try {
      const serverList = await this.matchingServiceArrary();
      const result = [];
      for (const service of serverList) {
        const res = await this.etcd.get(service.name).string();
        if (res.length === 0) {
          const list = {
            status: false,
            name: service.name,
            ip: service.ip,
            port: service.port,
          };
          result.push(list);
        } else {
          const list = {
            status: true,
            name: service.name,
            ip: service.ip,
            port: service.port,
          };
          result.push(list);
        }
      }
      return result;
    } catch (error) {
      this.logger.error(`服务查询故障 错误信息：${error}`);
    }
  }

  /**
   * 查询服务信息
   * 工具函数
   * @returns 服务信息
   */
  async matchingService(serviceName: string) {
    try {
      const config = await this.etcdConfigService.getConfig('dev-config');
      const res = { serviceId: '', ip: '', port: '' };
      if (serviceName === 'gateway-service') {
        res.serviceId = JSON.parse(config).GATEWAY_SERVICE_ID;
        res.ip = JSON.parse(config).GATEWAY_IP;
        res.port = JSON.parse(config).GATEWAY_TCP_PORT;
      } else if (serviceName === 'common-service') {
        res.serviceId = JSON.parse(config).COMMON_SERVICE_ID;
        res.ip = JSON.parse(config).COMMON_IP;
        res.port = JSON.parse(config).COMMON_TCP_PORT;
      } else if (serviceName === 'user-service') {
        res.serviceId = JSON.parse(config).USER_SERVICE_ID;
        res.ip = JSON.parse(config).USER_IP;
        res.port = JSON.parse(config).USER_TCP_PORT;
      } else if (serviceName === 'news-service') {
        res.serviceId = JSON.parse(config).NEWS_SERVICE_ID;
        res.ip = JSON.parse(config).NEWS_IP;
        res.port = JSON.parse(config).NEWS_TCP_PORT;
      }
      return res;
    } catch (error) {
      this.logger.error(`配置信息查询失败 错误信息：${error}`);
    }
  }
  async matchingServiceArrary() {
    try {
      const config = await this.etcdConfigService.getConfig('dev-config');
      const serverList = [];
      JSON.parse(config).SERVICE_LIST.forEach((i: any) => {
        if (i === 'gateway-service') {
          const datas = {
            name: i,
            ip: JSON.parse(config).GATEWAY_IP,
            port: JSON.parse(config).GATEWAY_TCP_PORT,
          };
          serverList.push(datas);
        } else if (i === 'user-service') {
          const datas = {
            name: i,
            ip: JSON.parse(config).USER_IP,
            port: JSON.parse(config).USER_TCP_PORT,
          };
          serverList.push(datas);
        } else if (i === 'common-service') {
          const datas = {
            name: i,
            ip: JSON.parse(config).NEWS_IP,
            port: JSON.parse(config).NEWS_TCP_PORT,
          };
          serverList.push(datas);
        } else {
          const datas = {
            name: i,
            ip: null,
            port: null,
          };
          serverList.push(datas);
        }
      });
      return serverList;
    } catch (error) {
      this.logger.error(`配置信息查询失败 错误信息：${error}`);
    }
  }
}
